﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.Script.Serialization;
using System.Text;
using System.Collections;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.IO;
using System.Reflection;



namespace Nova_Common
{
    public class clsJSON
    {

        /// 样式如下：
        //    {
        // 
        //    
        //        " Num_Service_Form ": " SZ201608303569 ",
        //        " Date_Create ": " 2016-08-30 13:25:19.140 ",
        //        " Status_Form ": "10",
        //        " ProductInfo ": [
        //            {
        //                " Name_Commodity ": “CO2C多功能互联网摄像机”,
        //                " Count_Commodity ": "1",
        //                " Price ": "169.00",
        //                " Total_Price ": "169.00"
        //            }，
        //           {
        //                " Name_Commodity ": “CO2C多功能互联网摄像机”,
        //                " Count_Commodity ": "1",
        //                " Price ": "169.00",
        //                " Total_Price ": "169.00"
        //            }
        //                         ]
        //          
        //         }
        /// <summary>
        /// dt为一行数据的表data 中的数据项，dtProduct为产品数据表，ProductInfo中的数据
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="dtProduct"></param>
        /// <returns></returns>
        public StringBuilder GetDataToJson(DataTable dt, DataTable dtProduct)
        {
            StringBuilder jsonString = new StringBuilder();
            jsonString.Append("{");
            //jsonString.Append("\"Data\" : {");


            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        
                            jsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[0][j].ToString().Replace("\"", "’") + "\",");
                        
                    }
                    //
                    jsonString.Append("\"orderItems\" : [");
                    #region dtProduct数据处理
                    if (dtProduct != null)
                    {
                        if (dtProduct.Rows.Count > 0)
                        {
                            for (int i = 0; i < dtProduct.Rows.Count; i++)
                            {
                                jsonString.Append("{ ");
                                for (int j = 0; j < dtProduct.Columns.Count; j++)
                                {

                                    jsonString.Append("\"" + dtProduct.Columns[j].ColumnName.ToString() + "\":" + "\"" + dtProduct.Rows[i][j].ToString().Replace("\"", "’") + "\",");

                                }

                                jsonString.Remove(jsonString.Length - 1, 1);
                                /*end Of String*/
                                if (i == dtProduct.Rows.Count - 1)
                                {
                                    jsonString.Append("} ");
                                }
                                else
                                {
                                    jsonString.Append("}, ");
                                }
                            }
                        }
                    }
                    #endregion

                    jsonString.Append("]");


                }
            }

            jsonString.Append("}");

            return jsonString;
        }

        public StringBuilder GetDataToJson(DataTable dt, string result, string msg, string fileNames)
        {
            StringBuilder jsonString = new StringBuilder();

            jsonString.Append("{ ");

            jsonString.Append("\"Result\":\"" + result + "\",");
            jsonString.Append("\"Msg\":\"" + msg + "\",");

            jsonString.Append("\"Data\" : [ ");

            #region 数据处理
            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        jsonString.Append("{ ");
                        for (int j = 0; j < dt.Columns.Count; j++)
                        {
                            if (fileNames.Contains((dt.Columns[j].ColumnName.ToString() + ",").ToString()))
                            {
                                jsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString().Replace("\"", "’") + "\",");
                            }
                        }
                        //  jsonString.ToString().TrimEnd(',');
                        //jsonString.d(jsonString.length() - 1);
                        jsonString.Remove(jsonString.Length - 1, 1);
                        /*end Of String*/
                        if (i == dt.Rows.Count - 1)
                        {
                            jsonString.Append("} ");
                        }
                        else
                        {
                            jsonString.Append("}, ");
                        }
                    }
                }
            }
            #endregion
            jsonString.Append("]}");

            return jsonString;
        }

        /// <summary>
        /// 获取json数据，直接将整个datatable转化成json数据
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string DataTableToJson(DataTable dt, bool isURL)
        {
            if (dt.Rows.Count == 0)
                return string.Empty;

            string[] columns = new string[dt.Columns.Count];
            for (int i = 0; i < dt.Columns.Count; i++)
                columns[i] = dt.Columns[i].ColumnName;
            return DataTableToJson(dt, columns, isURL);
        }

        /// <summary>
        /// 获取json数据，将datatable指定的列转化成json数据
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="columnNames"></param>
        /// <returns></returns>
        public static string DataTableToJson(DataTable dt, string[] columnNames, bool isURL)
        {
            if (dt.Rows.Count == 0)
                return string.Empty;

            return DataTableToJson(dt, columnNames, columnNames, isURL);
        }

        /// <summary>
        /// 获取json数据，将datatable指定的列转化成json数据，json数据列和指定列不同名，需要对应
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="columnNames">json数据列名（json数据参数名）</param>
        /// <param name="sourceColumnNames">datatable中的列名</param>
        /// <returns></returns>
        public static string DataTableToJson(DataTable dt, string[] columnNames, string[] sourceColumnNames, bool isURL)
        {
            StringBuilder sb = new StringBuilder();

            if (dt.Rows.Count == 0)
            {

            }
            else if (dt.Rows.Count == 1)
            {
                sb.Append(GetOneRowJSON(dt.Rows[0], columnNames, sourceColumnNames, isURL));
            }
            else
            {
                foreach (DataRow dr in dt.Rows)
                    sb.Append(GetOneRowJSON(dr, columnNames, sourceColumnNames, isURL) + ",");
            }

            return "[" + sb.ToString().Trim(',') + "]";
        }

        /// <summary>
        /// 获取json数据，将datatable指定的列转化成json数据，json数据列和指定列不同名，需要对应
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="columnNames">json数据列名（json数据参数名）</param>
        /// <param name="sourceColumnNames">datatable中的列名</param>
        /// <returns></returns>
        public static string DataTableToJsonSYH(DataTable dt, string[] columnNames, string[] sourceColumnNames)
        {
            StringBuilder sb = new StringBuilder();

            if (dt.Rows.Count == 0)
            {

            }
            else if (dt.Rows.Count == 1)
            {
                sb.Append(GetOneRowJSONSYH(dt.Rows[0], columnNames, sourceColumnNames));
            }
            else
            {
                foreach (DataRow dr in dt.Rows)
                    sb.Append(GetOneRowJSONSYH(dr, columnNames, sourceColumnNames) + ",");
            }

            return "[" + sb.ToString().Trim(',') + "]";
        }


        /// <summary>
        /// 将json数据转成DataTable
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static DataTable JsonToDataTable(string json)
        {
            DataTable dtRet = new DataTable();

            try
            {
                json = json.Trim();
                if (json[0] != '[')
                    json = "[" + json;
                if (json[json.Length - 1] != ']')
                    json = json + "]";

                JavaScriptSerializer jss = new JavaScriptSerializer();
                ArrayList arrList = jss.Deserialize<ArrayList>(json);

                if (arrList.Count > 0)
                {
                    foreach (Dictionary<string, object> arrRow in arrList)
                    {
                        if (dtRet.Columns.Count == 0)
                        {
                            foreach (string key in arrRow.Keys)
                            {
                                if (key.Equals("tagid_list"))
                                {
                                    continue;
                                }
                                dtRet.Columns.Add(key, arrRow[key].GetType());
                            }
                        }
                        DataRow dr = dtRet.NewRow();
                        foreach (string key in arrRow.Keys)
                        {
                            if (key.Equals("privilege") || key.Equals("tagid_list"))
                            {
                                continue;
                            }
                            dr[key] = System.Web.HttpUtility.UrlDecode(arrRow[key].ToString(), System.Text.Encoding.UTF8);
                        }
                        dtRet.Rows.Add(dr);
                    }
                }
                return dtRet;
            }
            catch (Exception exp)
            {
                return dtRet;
            }
        }

        /// <summary>
        /// 将json数据转成DataTable，指定转哪些列
        /// </summary>
        /// <param name="json"></param>
        /// <param name="columnNames"></param>
        /// <returns></returns>
        public static DataTable JsonToDataTable(string json, string[] columnNames)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            ArrayList arrList = jss.Deserialize<ArrayList>(json);
            DataTable dtRet = new DataTable();
            if (arrList.Count > 0)
            {
                foreach (Dictionary<string, object> arrRow in arrList)
                {
                    if (dtRet.Columns.Count == 0)
                    {
                        foreach (string columnName in columnNames)
                        {
                            if (arrRow.Keys.Contains(columnName))
                            {
                                dtRet.Columns.Add(columnName, arrRow[columnName].GetType());
                            }
                        }
                    }

                    DataRow dr = dtRet.NewRow();
                    foreach (DataColumn dc in dtRet.Columns)
                    {
                        dr[dc.ColumnName] = arrRow[dc.ColumnName];
                    }
                    dtRet.Rows.Add(dr);
                }
            }
            return dtRet;

        }

        /// <summary>
        /// 将json数据转成DataTable，指定将哪些json关键字按对应的列转
        /// </summary>
        /// <param name="json"></param>
        /// <param name="columnNames"></param>
        /// <param name="sourceColumnNames"></param>
        /// <returns></returns>
        public static DataTable JsonToDataTable(string json, string[] columnNames, string[] sourceColumnNames)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            ArrayList arrList = jss.Deserialize<ArrayList>(json);
            DataTable dtRet = new DataTable();
            if (arrList.Count > 0)
            {
                foreach (Dictionary<string, object> arrRow in arrList)
                {
                    if (dtRet.Columns.Count == 0)
                    {
                        for (int i = 0; i < columnNames.Length; i++)
                        {
                            if (arrRow.Keys.Contains(columnNames[i]))
                            {
                                dtRet.Columns.Add(sourceColumnNames[i], arrRow[columnNames[i]].GetType());
                            }
                        }
                    }

                    DataRow dr = dtRet.NewRow();

                    for (int i = 0; i < columnNames.Length; i++)
                    {
                        if (arrRow.Keys.Contains(columnNames[i]))
                        {
                            dr[sourceColumnNames[i]] = arrRow[columnNames[i]];
                        }
                    }
                    dtRet.Rows.Add(dr);
                }
            }
            return dtRet;
        }


        /// <summary>
        /// 获取一行记录集的json数据
        /// </summary>
        /// <param name="dr"></param>
        /// <param name="columnNames"></param>
        /// <param name="sourceColumnNames"></param>
        /// <returns></returns>
        public static string GetOneRowJSON(DataRow dr, string[] columnNames, string[] sourceColumnNames, bool isURL = true)
        {
            string Template = "{0}:'{1}',";
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < columnNames.Length; i++)
            {
                if (isURL)
                {
                    sb.AppendFormat(Template, columnNames[i], System.Web.HttpUtility.UrlEncode(dr[sourceColumnNames[i]].ToString()));

                }
                else { sb.AppendFormat(Template, columnNames[i], dr[sourceColumnNames[i]].ToString()); }

            }

            return "{" + sb.ToString().Trim(',') + "}";
        }

        /// <summary>
        /// 获取一行记录集的json数据
        /// </summary>
        /// <param name="dr"></param>
        /// <param name="columnNames"></param>
        /// <param name="sourceColumnNames"></param>
        /// <returns></returns>
        public static string GetOneRowJSONSYH(DataRow dr, string[] columnNames, string[] sourceColumnNames)
        {
            string Template = "\"{0}\":\"{1}\",";
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < columnNames.Length; i++)
            {
                sb.AppendFormat(Template, columnNames[i], System.Web.HttpUtility.UrlEncode(dr[sourceColumnNames[i]].ToString()));
                //sb.AppendFormat(Template, columnNames[i], dr[sourceColumnNames[i]].ToString());
            }

            return "{" + sb.ToString().Trim(',') + "}";
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static DataTable ProvinceInfoToDataTable(string json)
        {
            DataTable dtRet = new DataTable();

            dtRet.Columns.Add("Name_Province", typeof(string));
            dtRet.Columns.Add("TSPCode_Province", typeof(string));

            json = json.Trim();
            string[] s1 = json.Split('|');
            foreach (string s in s1)
            {
                string[] s2 = s.Split(',');
                string sname = s2[0];
                string scode = s2[1];

                DataRow dr = dtRet.NewRow();


                dtRet.Rows.Add(sname, scode);

            }

            return dtRet;
        }


        /// <summary>
        /// 下单取卡券信息
        /// </summary>
        /// <param name="setJson"></param>
        /// <param name="least_cost"></param>
        /// <param name="reduce_cost"></param>
        public static void GetCashCost(string setJson, out string least_cost, out string reduce_cost)
        {
            try
            {
                JObject card = (JObject)JsonConvert.DeserializeObject(setJson);
                string strcard = card["card"].ToString();
                JObject cash = (JObject)JsonConvert.DeserializeObject(strcard);
                string strCash = cash["cash"].ToString();
                JObject cashCost = (JObject)JsonConvert.DeserializeObject(strCash);
                //最低消费金额分
                least_cost = cashCost["least_cost"].ToString();
                //减免金额分
                reduce_cost = cashCost["reduce_cost"].ToString();
            }
            catch (Exception e)
            {
                least_cost = "";
                reduce_cost = "";
            }
        }


        //解析卡券信息
        public static void GetConsume(string setJson, out string getResult, out string sReInfo)
        {
            /*
             {"errcode":0,"errmsg":"ok","card":
{"card_id":"pUyW6tygNi46l5luRKksFXT3ovII","begin_time":1461168000,"end_time":1463759999},"openid":"oUyW6t5Mozu2Jv7y9tx5803Un884","can_consume":true,"user_card_status":
"NORMAL"}
             */
            getResult = "";
            sReInfo = "";
            try
            {
                JObject card = (JObject)JsonConvert.DeserializeObject(setJson);
                string errcode = card["errcode"].ToString();
                string cards = card["card"].ToString();

                if (errcode == "0")
                {

                    getResult = "1";

                }
                else
                {
                    getResult = "-1";
                    JObject cash = (JObject)JsonConvert.DeserializeObject(cards);
                    string user_card_status = card["user_card_status"].ToString();
                    switch (user_card_status)
                    {
                        //已核销
                        case "CONSUMED":
                            sReInfo = "该卡券已被核销,不能使用！";
                            break;

                        //已过期
                        case "EXPIRE":
                            sReInfo = "该卡券已过期,不能使用！";
                            break;

                        //转赠中
                        case "GIFTING":
                            sReInfo = "该卡券转赠中，不能使用！";
                            break;
                        default:
                            sReInfo = "该卡券处于非法状态，不能使用！";
                            break;
                    }

                }


            }
            catch (Exception ex)
            {
                getResult = "-1";
                sReInfo = "该卡券处于非法状态，不能使用！";
            }
        }




        /// <summary>
        ///  从一个对象信息生成Json串
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public string ObjectToJson(object obj)
        {
            return JsonConvert.SerializeObject(obj);
        }

        /// <summary>
        /// 从一个Json串生成对象信息
        /// </summary>
        /// <param name="jsonString"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public object JsonToObject(string jsonString, object obj)
        {
            return JsonConvert.DeserializeObject(jsonString, obj.GetType());
        }

        /// <summary>
        /// Json串生成对象信息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <returns></returns>
        public static T DeserializeJsonToObject<T>(string json) where T : class
        {
            T t = default(T);
            JsonSerializer serializer = new JsonSerializer();
            StringReader sr = new StringReader(json);
            using (JsonTextReader reader = new JsonTextReader(sr))
            {
                object o = serializer.Deserialize(reader, typeof(T));
                t = o as T;
                return t;
            }
        }

        
    }
}
